import router, { asyncRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const token = store.state.user.token
  const whiteList = ['/login', '/404']
  if (token) {
    if (to.path === '/login') {
      Message.info('你已经登录，请不要重复登录')
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log(menus)
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenus', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.error('你还没有登录，请登录')
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
